import axios from 'axios'

// 创建axios
const service = axios.create({
	// #ifdef H5
	baseURL: '/api',
	// #endif
	// #ifndef H5
	baseURL: 'https://32a0499x88.qicp.vip/',
	// #endif
	timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
	config => {
		// 拦截请求
		uni.showLoading({
			title: '加载中...',
			icon: 'none'
		})
		const token = uni.getStorageSync('Authorization')
		config.headers['Authorization'] = token
		return config
	},
	err => {
		uni.hideLoading()
		uni.showToast({
			title: data.msg,
			icon: 'none'
		})
		return Promise.reject(err)
	}
)

// 响应拦截器
service.interceptors.response.use(
	response => {
		const data = response.data
		uni.hideLoading()
		return data
	},
	err => {
		uni.hideLoading()
		uni.showToast({
			title: data.msg,
			icon: 'none'
		})
		return Promise.reject(err)
	}
)

// 解决axios在小程序和app中无效的问题
// #ifndef H5
service.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}
// #endif

export default service